import { ExecFileOptions, spawn } from 'child_process'
import { BaseEncodingOptions, existsSync } from 'fs'
import { platform, } from 'os'
import { resolve } from 'path'
import config from './config'
import { installArduino } from './install'
import { Name, RUNPATH } from './interface'

const P: RUNPATH = {
    arduino: {
        win32: resolve(config.basePath, 'Arduino.app/Contents/java/arduino-builder'),
        linux: resolve(config.basePath, 'arduino/arduino-builder'),
        darwin: resolve(config.basePath, 'arduino/arduino-builder')
    },
    leap: {
        win32: resolve()
    },
    arduinodrivers: {

    },
    cpp: {}
}

function findpath(d: string) {
    if (!d) {
        console.log('没有这个系统的软件')
        return false
    }
    if (!existsSync(d)) {
        return false
    }
    return true
}



export async function Runarduino() {
    const path = P.arduino?.[platform()]
    if (!path) return
    if (!findpath(path)) {
        const d = await installArduino()
        if (!d) return Promise.reject('安装失败')
    }
    return runFile(path, [ardu_start[8]])
}

const ardu_start = [
    "--verify", //验证
    "--upload", //上传
    "--board", //板子的名称
    "--port", //板子的串口号
    "--pref", //首选项
    "--verbose", //详细信息
    "--preserve-temp-files", //保存 .hex 文件
    "FILE.ino", //文件路径
    "--version" // 
];

// export const geiArduinoCmd = function (path: string, build, board = "arduino:avr:uno", textIno: string, build_path: string, port: number,) {
//     if (port == null) {
//         return `"${path}" ${build} ${ardu_start[2]} ${board}    -v --pref "build.path=${build_path}"  --preserve-temp-files "${textIno}"`;
//     } else {
//         return `"${path}" ${build} ${ardu_start[2]} ${board} ${ardu_start[3]} ${port} -v --pref "build.path=${build_path}" --preserve-temp-files "${textIno}"`;
//     }
// };



export function runFile(path: string, readonly: string[] = [], options?: (BaseEncodingOptions & ExecFileOptions)) {
    const e = spawn(path, readonly, options)
    return e
}

/**
 * 查看软件是否存运行程序
 * @param name 
 */
export function findSoftware(name: Name) {
    const t = P[name]
    if (t) {
        let c = t[platform()]
        if (c) {
            return existsSync(c)
        }
    }
    return false
}
